package com.droidzxy.membership;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.huawei.agconnect.auth.AGConnectAuth;
import com.huawei.agconnect.auth.PhoneUser;
import com.huawei.agconnect.auth.SignInResult;
import com.huawei.agconnect.auth.VerifyCodeResult;
import com.huawei.agconnect.auth.VerifyCodeSettings;
import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.huawei.hmf.tasks.Task;
import com.huawei.hmf.tasks.TaskExecutors;

import java.util.Locale;

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener{
    private EditText edtPhone;
    private EditText edtPassword;
    private EditText edtRePassword;
    private EditText edtVerify;

    private Button btnBack;
    private Button btnSend;
    private Button btnRegister;

    private ImageView imgBack;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(getResources().getColor(R.color.statuscolor));
        }

        edtPhone = findViewById(R.id.edt_phone);
        edtPassword = findViewById(R.id.edt_password);
        edtRePassword = findViewById(R.id.edt_repassword);
        edtVerify = findViewById(R.id.edt_verify);


        btnSend = findViewById(R.id.btn_send);
        btnSend.setOnClickListener(this);
        btnRegister = findViewById(R.id.btn_register);
        btnRegister.setOnClickListener(this);

        imgBack = findViewById(R.id.img_back);
        imgBack.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_send:
                if(checkInputForVerify()) {
                    edtVerify.setText("");
                    sendVerificationCode();
                    btnSend.setEnabled(false);
                    btnSend.setBackgroundColor(getColor(android.R.color.darker_gray));
                    new CountDownTimer(30000, 1000) {

                        public void onTick(long millisUntilFinished) {
                            btnSend.setText(String.valueOf(millisUntilFinished / 1000) +" s");

                        }

                        public void onFinish() {
                            btnSend.setBackground(ContextCompat.getDrawable(getBaseContext(), R.drawable.rectangle));
                            btnSend.setEnabled(true);
                            btnSend.setText("获取验证码");
                        }
                    }.start();
                }
                break;
            case R.id.btn_register:
                if(checkInput()) {
                    register();
                }
                break;
            case R.id.img_back:
                onBackPressed();
                break;

        }
    }


    private void sendVerificationCode() {
        VerifyCodeSettings settings = VerifyCodeSettings.newBuilder()
                .action(VerifyCodeSettings.ACTION_REGISTER_LOGIN)// action type
                .sendInterval(30) //shortest send interval ，30-120s
                .locale(Locale.SIMPLIFIED_CHINESE) //optional,must contain country and language eg:zh_CN
                .build();

            String countryCode = "86";
            String phoneNumber = edtPhone.getText().toString().trim();
            // apply for a verification code by phone, indicating that the phone is owned by you.
            Task<VerifyCodeResult> task = AGConnectAuth.getInstance().requestVerifyCode(countryCode, phoneNumber, settings);
            task.addOnSuccessListener(TaskExecutors.uiThread(), new OnSuccessListener<VerifyCodeResult>() {
                @Override
                public void onSuccess(VerifyCodeResult verifyCodeResult) {
                    Toast.makeText(RegisterActivity.this, "请求验证码成功", Toast.LENGTH_SHORT).show();
                    //You need to get the verification code from your phone
                }
            }).addOnFailureListener(TaskExecutors.uiThread(), new OnFailureListener() {
                @Override
                public void onFailure(Exception e) {
                    Toast.makeText(RegisterActivity.this, "requestVerifyCode fail:" + e, Toast.LENGTH_SHORT).show();
                }
            });

    }

    private void register() {
        String countryCode = "86";
        String phoneNumber = edtPhone.getText().toString().trim();
        String password = edtPassword.getText().toString().trim();
        String verifyCode = edtVerify.getText().toString().trim();
        // build phone user
        PhoneUser phoneUser = new PhoneUser.Builder()
                .setCountryCode(countryCode)
                .setPhoneNumber(phoneNumber)
                .setPassword(password)//optional
                .setVerifyCode(verifyCode)
                .build();
        // create phone user
        AGConnectAuth.getInstance().createUser(phoneUser)
                .addOnSuccessListener(new OnSuccessListener<SignInResult>() {
                    @Override
                    public void onSuccess(SignInResult signInResult) {
                        // After a user is created, the user has logged in by default.
                        startActivity(new Intent(RegisterActivity.this, MainActivity.class));
                        RegisterActivity.this.finish();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(Exception e) {
                        Toast.makeText(RegisterActivity.this, "createUser fail:" + e, Toast.LENGTH_LONG).show();
                    }
                });
    }

    private boolean checkInput() {
        boolean formatOK = true;
        String msg = "";
        if(edtPhone.getText().length() != 11) {
            formatOK = false;
            msg = "手机号错误";
        } else if(edtPassword.getText().length() == 0) {
            formatOK = false;
            msg = "密码不能为空";
        } else if(!edtRePassword.getText().toString().equals(edtPassword.getText().toString())) {
            formatOK = false;
            msg = "两次密码不相同";
        } else if(edtVerify.getText().length() == 0) {
            formatOK = false;
            msg = "验证码不能为空";
        }
        if(formatOK == false) {
            Toast.makeText(RegisterActivity.this, msg, Toast.LENGTH_LONG).show();
        }
        return formatOK;
    }

    private boolean checkInputForVerify() {
        boolean formatOK = true;
        String msg = "";
        if(edtPhone.getText().length() != 11) {
            formatOK = false;
            msg = "手机号错误";
        }
        return formatOK;
    }



}